<?php

class FilePickerWidget extends CInputWidget {

    public $assets;
    public $config;
    public $model;
    public $attribute;

    public function init() {
        parent::run();
        $assetObj = Yii::app()->getAssetManager();
        $assetObj->newFileMode = 0644; //fix bug on Matbao hosting
        $assetObj->newDirMode = 0755; //fix bug on Matbao hosting

        $path = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'assets' . DIRECTORY_SEPARATOR;
        $this->assets = $assetObj->publish($path);
    }

    public function run() {
        //set $_SESSION
        $_SESSION['file_manager'] = $this->config;
        
        //register Css & Script
        $cs = Yii::app()->getClientScript();
        $id = get_class($this->model) . '_' . $this->attribute;

        $cs->registerScript('file-picker-' . $id, "
$('#$id').click(function() {
    var dialogID = '#null';

    $(dialogID).unbind('assignLink');
    $(dialogID).bind('assignLink', function() {
        var link = $(dialogID).data('link');
        if (link !== undefined) {
            $('#$id').val(link);
        }
    });

    url = '$this->assets/elfinder.php'
    loadFrame(url, dialogID, 900, 550, '', 'frameLinks', 'File picker');
});", CClientScript::POS_END);
        
        echo CHtml::activeTextField($this->model, $this->attribute, array(
            'id' => $id,
            'class' => 'filePicker text small',
        ));
        echo CHtml::link('Clear', 'javascript:clearTextField("' . $id . '")', array(
            'style' => 'margin-left: 10px;',
        ));
    }
    
}